Security News
Research
Data Theft Repackaged: A Case Study in Malicious Wrapper Packages on npm
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
rehype-sanitize
Advanced tools
The rehype-sanitize package is a plugin for the rehype ecosystem that allows you to sanitize HTML. It is used to clean up and secure HTML content by removing potentially harmful elements and attributes, making it safe to use in web applications.
Basic Sanitization
This feature allows you to sanitize basic HTML content by removing potentially harmful elements like <script> tags. The example code demonstrates how to use rehype-sanitize to clean up an HTML string.
const rehype = require('rehype');
const rehypeSanitize = require('rehype-sanitize');
const html = '<div><script>alert("XSS")</script><p>Hello World</p></div>';
rehype()
.use(rehypeSanitize)
.process(html)
.then((file) => {
console.log(String(file));
});
Custom Schema
This feature allows you to use a custom schema for sanitization. The example code demonstrates how to use a GitHub-flavored schema to sanitize HTML content.
const rehype = require('rehype');
const rehypeSanitize = require('rehype-sanitize');
const schema = require('hast-util-sanitize/lib/github');
const html = '<div><script>alert("XSS")</script><p>Hello World</p></div>';
rehype()
.use(rehypeSanitize, schema)
.process(html)
.then((file) => {
console.log(String(file));
});
Customizing Allowed Elements
This feature allows you to customize the allowed elements and attributes in the HTML content. The example code demonstrates how to allow only <p>, <b>, and <i> tags and the 'className' attribute.
const rehype = require('rehype');
const rehypeSanitize = require('rehype-sanitize');
const schema = {
tagNames: ['p', 'b', 'i'],
attributes: {
'*': ['className']
}
};
const html = '<div class="container"><p class="text">Hello <b>World</b></p></div>';
rehype()
.use(rehypeSanitize, schema)
.process(html)
.then((file) => {
console.log(String(file));
});
sanitize-html is a library for cleaning up user-submitted HTML, preserving whitelisted elements and attributes while removing potentially harmful content. It offers a high degree of customization and is widely used for sanitizing HTML in web applications. Compared to rehype-sanitize, sanitize-html provides more granular control over the sanitization process and is not tied to the rehype ecosystem.
DOMPurify is a fast, tolerant, and secure client-side HTML, MathML, and SVG sanitizer. It works in all modern browsers and can be used to clean up HTML content before rendering it in the DOM. DOMPurify is known for its performance and security features, making it a popular choice for client-side sanitization. Unlike rehype-sanitize, which is a plugin for the rehype ecosystem, DOMPurify is a standalone library.
xss is a module used to filter input from users to prevent XSS attacks. It provides a set of default rules for sanitizing HTML and allows for customization of these rules. The xss library is designed to be simple and effective, making it a good choice for server-side sanitization. Compared to rehype-sanitize, xss is more focused on preventing XSS attacks and is not part of the rehype ecosystem.
rehype plugin to sanitize HTML.
This package is a unified (rehype) plugin to make sure HTML is safe.
It drops anything that isn’t explicitly allowed by a schema (defaulting to how
github.com
works).
unified is a project that transforms content with abstract syntax trees (ASTs). rehype adds support for HTML to unified. hast is the HTML AST that rehype uses. This is a rehype plugin that transforms hast.
It’s recommended to sanitize your HTML any time you do not completely trust authors or the plugins being used.
This plugin is built on hast-util-sanitize
, which cleans
hast syntax trees.
rehype focusses on making it easier to transform content by abstracting such
internals away.
This package is ESM only. In Node.js (version 12.20+, 14.14+, or 16.0+), install with npm:
npm install rehype-sanitize
In Deno with Skypack:
import rehypeSanitize from 'https://cdn.skypack.dev/rehype-sanitize@5?dts'
In browsers with Skypack:
<script type="module">
import rehypeSanitize from 'https://cdn.skypack.dev/rehype-sanitize@5?min'
</script>
Say we have the following file index.html
:
<div onmouseover="alert('alpha')">
<a href="jAva script:alert('bravo')">delta</a>
<img src="x" onerror="alert('charlie')">
<iframe src="javascript:alert('delta')"></iframe>
<math>
<mi xlink:href="data:x,<script>alert('echo')</script>"></mi>
</math>
</div>
<script>
require('child_process').spawn('echo', ['hack!']);
</script>
And our module example.js
looks as follows:
import {read} from 'to-vfile'
import {unified} from 'unified'
import rehypeParse from 'rehype-parse'
import rehypeSanitize from 'rehype-sanitize'
import rehypeStringify from 'rehype-stringify'
main()
async function main() {
const file = await unified()
.use(rehypeParse, {fragment: true})
.use(rehypeSanitize)
.use(rehypeStringify)
.process(await read('index.html'))
console.log(String(file))
}
Now running node example.js
yields:
<div>
<a>delta</a>
<img src="x">
</div>
This package exports the following identifiers: defaultSchema
.
The default export is rehypeSanitize
.
unified().use(rehypeSanitize[, schema])
Sanitize HTML.
schema
Sanitation schema that defines if and how nodes and properties should be
cleaned.
The default schema is exported as defaultSchema
.
This option is a bit advanced as it requires knowledge of ASTs, so we defer
to the documentation available for Schema
in hast-util-sanitize
.
DOM clobbering is an attack in which malicious HTML confuses an application by
naming elements, through id
or name
attributes, such that they overshadow
presumed properties in window
(the global scope in browsers).
DOM clobbering often occurs when user content is used to generate heading IDs.
To illustrate, say we have this browser.js
file:
console.log(current)
And our module example.js
contains:
import {promises as fs} from 'node:fs'
import {unified} from 'unified'
import rehypeParse from 'rehype-parse'
import rehypeStringify from 'rehype-stringify'
main()
async function main() {
const browser = String(await fs.readFile('browser.js'))
const document = `<a name="old"></a>
<h1 id="current">Current</h1>
${`<p>${'Lorem ipsum dolor sit amet. '.repeat(20)}</p>\n`.repeat(20)}
<p>Link to <a href="#current">current</a>, link to <a href="#old">old</a>.`
const file = await unified()
.use(rehypeParse, {fragment: true})
.use(() => (tree) => {
tree.children.push({
type: 'element',
tagName: 'script',
properties: {type: 'module'},
children: [{type: 'text', value: browser}]
})
})
.use(rehypeStringify)
.process(document)
await fs.writeFile('output.html', file.value)
}
This code processes HTML, inlines our browser script into it, and writes it out.
The input HTML models how markdown often looks on platforms like GitHub, which
allow heading IDs to be generated from their text and embedded HTML (including
<a name="old"></a>
, which can be used to create anchors for renamed headings
to prevent links from breaking).
The generated HTML looks like:
<a name="old"></a>
<h1 id="current">Current</h1>
<p>Lorem ipsum dolor sit amet.<!--…--></p>
<p>Link to <a href="#current">current</a>, link to <a href="#old">old</a>.</p>
<script type="module">console.log(current)</script>
When you run this code locally, open the generated output.html
, you can
observe that the links at the bottom work, but also that the <h1>
element
is printed to the console (the clobbering).
rehype-sanitize
solved the clobbering by prefixing every id
and name
attribute with 'user-content-'
.
Changing example.js
:
@@ -15,6 +15,7 @@ ${`<p>${'Lorem ipsum dolor sit amet. '.repeat(20)}</p>\n`.repeat(20)}
const file = await unified()
.use(rehypeParse, {fragment: true})
+ .use(rehypeSanitize)
.use(() => (tree) => {
tree.children.push({
type: 'element',
Now yields:
-<a name="old"></a>
-<h1 id="current">Current</h1>
+<a name="user-content-old"></a>
+<h1 id="user-content-current">Current</h1>
But this introduces another problem as the links are now broken.
It could perhaps be solved by changing all links, but that would make the links
rather ugly, and we’d need to track what IDs we have outside of the user content
on our pages too.
Alternatively, and what arguably looks better, we could rewrite pretty links to
their safe but ugly prefixed elements.
This is what GitHub does.
Replace browser.js
with the following:
// Page load (you could wrap this in a DOM ready if the script is loaded early).
hashchange()
// When URL changes.
window.addEventListener('hashchange', hashchange)
// When on the URL already, perhaps after scrolling, and clicking again, which
// doesn’t emit `hashchange`.
document.addEventListener(
'click',
(event) => {
if (
event.target &&
event.target instanceof HTMLAnchorElement &&
event.target.href === location.href &&
location.hash.length > 1
) {
setTimeout(() => {
if (!event.defaultPrevented) {
hashchange()
}
})
}
},
false
)
function hashchange() {
/** @type {string|undefined} */
let hash
try {
hash = decodeURIComponent(location.hash.slice(1)).toLowerCase()
} catch {
return
}
const name = 'user-content-' + hash
const target =
document.getElementById(name) || document.getElementsByName(name)[0]
if (target) {
setTimeout(() => {
target.scrollIntoView()
}, 0)
}
}
Math can be enabled in rehype by using the plugins
rehype-katex
or rehype-mathjax
.
The operate on span
s and div
s with certain classes and inject complex markup
and of inline styles, most of which this plugin will remove.
Say our module example.js
contains:
import {unified} from 'unified'
import rehypeParse from 'rehype-parse'
import rehypeKatex from 'rehype-katex'
import rehypeSanitize from 'rehype-sanitize'
import rehypeStringify from 'rehype-stringify'
main()
async function main() {
const file = await unified()
.use(rehypeParse, {fragment: true})
.use(rehypeKatex)
.use(rehypeSanitize)
.use(rehypeStringify)
.process('<span class="math math-inline">L</span>')
console.log(String(file))
}
Running that yields:
<span><span><span>LL</span><span aria-hidden="true"><span><span></span><span>L</span></span></span></span></span>
It is possible to pass a schema which allows MathML and inline styles, but it
would be complex, and allows all inline styles, which is unsafe.
Alternatively, and arguably better, would be to first sanitize the HTML,
allowing only the specific classes that rehype-katex
and rehype-mathjax
use,
and then using those plugins:
@@ -1,7 +1,7 @@
import {unified} from 'unified'
import rehypeParse from 'rehype-parse'
import rehypeKatex from 'rehype-katex'
-import rehypeSanitize from 'rehype-sanitize'
+import rehypeSanitize, {defaultSchema} from 'rehype-sanitize'
import rehypeStringify from 'rehype-stringify'
main()
@@ -9,8 +9,21 @@ main()
async function main() {
const file = await unified()
.use(rehypeParse, {fragment: true})
+ .use(rehypeSanitize, {
+ ...defaultSchema,
+ attributes: {
+ ...defaultSchema.attributes,
+ div: [
+ ...(defaultSchema.attributes.div || []),
+ ['className', 'math', 'math-display']
+ ],
+ span: [
+ ...(defaultSchema.attributes.span || []),
+ ['className', 'math', 'math-inline']
+ ]
+ }
+ })
.use(rehypeKatex)
- .use(rehypeSanitize)
.use(rehypeStringify)
.process('<span class="math math-inline">L</span>')
Highlighting, for example with rehype-highlight
, can be
solved similar to how math is solved (see previous example).
That is, use rehype-sanitize
and allow the classes needed for highlighting,
and highlight afterwards:
import {unified} from 'unified'
import rehypeParse from 'rehype-parse'
import rehypeHighlight from 'rehype-highlight'
import rehypeSanitize, {defaultSchema} from './index.js'
import rehypeStringify from 'rehype-stringify'
main()
async function main() {
const file = await unified()
.use(rehypeParse, {fragment: true})
.use(rehypeSanitize, {
...defaultSchema,
attributes: {
...defaultSchema.attributes,
code: [
...(defaultSchema.attributes.code || []),
// List of all allowed languages:
['className', 'language-js', 'language-css', 'language-md']
]
}
})
.use(rehypeHighlight, {subset: false})
.use(rehypeStringify)
.process('<pre><code className="language-js">console.log(1)</code></pre>')
console.log(String(file))
}
Alternatively, it’s possible to make highlighting safe by allowing all the classes used on tokens. Modifying the above code like so:
async function main() {
const file = await unified()
.use(rehypeParse, {fragment: true})
+ .use(rehypeHighlight, {subset: false})
.use(rehypeSanitize, {
...defaultSchema,
attributes: {
...defaultSchema.attributes,
- code: [
- ...(defaultSchema.attributes.code || []),
- // List of all allowed languages:
- ['className', 'hljs', 'language-js', 'language-css', 'language-md']
+ span: [
+ ...(defaultSchema.attributes.span || []),
+ // List of all allowed tokens:
+ ['className', 'hljs-addition', 'hljs-attr', 'hljs-attribute', 'hljs-built_in', 'hljs-bullet', 'hljs-char', 'hljs-code', 'hljs-comment', 'hljs-deletion', 'hljs-doctag', 'hljs-emphasis', 'hljs-formula', 'hljs-keyword', 'hljs-link', 'hljs-literal', 'hljs-meta', 'hljs-name', 'hljs-number', 'hljs-operator', 'hljs-params', 'hljs-property', 'hljs-punctuation', 'hljs-quote', 'hljs-regexp', 'hljs-section', 'hljs-selector-attr', 'hljs-selector-class', 'hljs-selector-id', 'hljs-selector-pseudo', 'hljs-selector-tag', 'hljs-string', 'hljs-strong', 'hljs-subst', 'hljs-symbol', 'hljs-tag', 'hljs-template-tag', 'hljs-template-variable', 'hljs-title', 'hljs-type', 'hljs-variable'
+ ]
]
}
})
- .use(rehypeHighlight, {subset: false})
.use(rehypeStringify)
.process('<pre><code className="language-js">console.log(1)</code></pre>')
This package is fully typed with TypeScript.
It exports an Options
type, which specifies the interface of the accepted
options.
Projects maintained by the unified collective are compatible with all maintained versions of Node.js. As of now, that is Node.js 12.20+, 14.14+, and 16.0+. Our projects sometimes work with older versions, but this is not guaranteed.
This plugin works with rehype-parse
version 3+, rehype-stringify
version 3+,
rehype
version 5+, and unified
version 6+.
The defaults are safe but improper use of rehype-sanitize
can open you up to a
cross-site scripting (XSS) attack.
Use rehype-sanitize
after the last unsafe thing: everything after
rehype-sanitize
could be unsafe (but is fine if you do trust it).
hast-util-sanitize
— utility to sanitize hastrehype-format
— format HTMLrehype-minify
— minify HTMLSee contributing.md
in rehypejs/.github
for ways
to get started.
See support.md
for ways to get help.
This project has a code of conduct. By interacting with this repository, organization, or community you agree to abide by its terms.
FAQs
rehype plugin to sanitize HTML
The npm package rehype-sanitize receives a total of 236,704 weekly downloads. As such, rehype-sanitize popularity was classified as popular.
We found that rehype-sanitize demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Research
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
Research
Security News
Attackers used a malicious npm package typosquatting a popular ESLint plugin to steal sensitive data, execute commands, and exploit developer systems.
Security News
The Ultralytics' PyPI Package was compromised four times in one weekend through GitHub Actions cache poisoning and failure to rotate previously compromised API tokens.